const express = require('express'),
      router = express.Router(),
      mysql = require("../routes/SQL"),
        url = require("url"),
        path = require("path"),
        fs = require("fs")
router.get('/', function(req, res, next) {
    handle(req,res,"/")

})
/* GET home page. */
router.get('/login', function(req, res, next) {
  const account = req.query.user_account; //获取用户账户
  const passwd = req.query.user_passwd;//获取用户密码
  let data = mysql.mysql({account:account,passwd:passwd})
data.then((msg)=>{
    console.log(msg[0])
    if (msg[0].status === 200){
         handle(req,res,"/login")
        // res.render('index', { title: {msg:"登录成功",account:msg[0].userinfo.id,passwd:msg[0].userinfo.passwd,name:msg[0].userinfo.name} });
    }
    else {
        res.redirect("http://127.0.0.1:8000")
        //  res.render('login', { message: "登录" });
    }


})

      // var username = request.body.login;

});
function handle(req,res,flag) {
          let pathname = "../views" + url.parse(req.url).pathname;
          console.log("sss:"+(pathname.charAt(pathname.length-1)));
    if (flag ==="/"){
        pathname+="login.html";
    }
    else if(flag ==="/login"){
        pathname+="/index.html";
    }
    console.log(pathname)
    // console.log(pathname)
    fs.exists(pathname,function(exists){
        console.log(exists)
        if(exists) {
            switch (path.extname(pathname)) {
                case ".html":
                    // res.writeHead(200, {"Content-Type": "text/html"});
                    break;
                case ".js":
                    // res.writeHead(200, {"Content-Type": "text/javascript"});
                    break;
                case ".css":
                    // res.writeHead(200, {"Content-Type": "text/css"});
                    break;
                case ".gif":
                    // res.writeHead(200, {"Content-Type": "image/gif"});
                    break;
                case ".jpg":
                    // res.writeHead(200, {"Content-Type": "image/jpeg"});
                    break;
                case ".png":
                    // res.writeHead(200, {"Content-Type": "image/png"});
                    break;
                case ".mp3":
                    // res.writeHead(200, {"Content-Type": "audio/mp3"});
                    break;
                default:
                // res.writeHead(200, {"Content-Type": "application/octet-stream"});
            }

            fs.readFile(pathname, function (err, data) {
                res.end(data);
            });
        }
    });
    // res.render('login', {title:{msg:"登录"}});
}


module.exports = router;
